/**
 * 
 */
package org.ycsoft.PathComputation;

import java.util.*;

/**
 * A priority queue implementation to use in the Dijkstra algorithm implementation 
 * @author allad
 *
 */
public class StopPriorityQueue {
	
	
	private class QueueElementComparator implements Comparator<PriorityQueueItem>{

		public int compare(PriorityQueueItem o1, PriorityQueueItem o2) {
			if(o1.getDistance() < o2.getDistance())
				return -1;
			else if(o1.getDistance() == o2.getDistance())
				return 0;
			else return 1;
		}
		
	}
	
	private PriorityQueue<PriorityQueueItem> innerQueue ;
	
	public StopPriorityQueue(int nbStops){
		innerQueue = new PriorityQueue<PriorityQueueItem>(nbStops,new QueueElementComparator());
	}
	
	/**
	 * Remplit la queue de priorite avec les stops. 
	 * @param stopsDb the collection of stops in the map
	 * @param root the root stop 
	 */
	public void buildHeap(StopDB stopsDb,Stop root){
		if(stopsDb == null)
			return;
		for(Stop stop : stopsDb.getStopsSet()){
			if(stop == root)
				insert(root,0);
			else insert(stop,Commons.INFINITY);
		}
		
	}
	
	/**
	 * Extrait le stop qui a la distance la distance minimun
	 * @return 
	 */
	public PriorityQueueItem extractMin(){
		return innerQueue.poll();
	}	
	
	
	/**
	 * @return True if the queue is empty. False otherwise
	 */
	public boolean isEmpty(){
		//la queue est vide si la prochaine position disponible est la position 0
		return (innerQueue.size() == 0); 
	}
	
	
	/**
	 * @return The number of items in this queue
	 */
	public int size(){
		return innerQueue.size();
	}
	
	/**
	 * Définit la distance d'un stop a la valeur passee.
	 * @param stop
	 * @param newKey
	 * @return
	 */
	public boolean changeKey(Stop stop,int newKey){
		boolean b1 = innerQueue.contains(stop);
		boolean b2 = innerQueue.remove(stop);
		PriorityQueueItem item = new PriorityQueueItem(stop,newKey);
		boolean retVal =  innerQueue.add(item);
		return retVal;
	}
	
	
	/**
	 * Insert a new stop in the queue.
	 * @param stop
	 */
	private void insert(Stop stop,int key){		
		PriorityQueueItem newItem = new PriorityQueueItem(stop,key);
		innerQueue.add(newItem);
	}

}

